package myTest;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by 杨志远 on 2017/6/5
 * email faryangsh@163.com.
 */
public class FairAndUnfairTest {
    private static Lock fairLock=new ReentrantLock2(true);
    private static Lock unfairlock=new ReentrantLock2(false);

    @Test
    public void fair(){
        long start = System.currentTimeMillis();
        testLock(fairLock);
        System.out.print(System.currentTimeMillis()-start);
    }

    @Test
    public void unfair(){
        testLock(unfairlock);
    }

    private void testLock(Lock lock){
        Job job1 = new Job(lock);
        Job job2 = new Job(lock);
        Job job3 = new Job(lock);
        Job job4 = new Job(lock);
        Job job5 = new Job(lock);
        job1.start();
        job2.start();
        job3.start();
        job4.start();
        job5.start();
    }
    private static class Job extends Thread{
        private Lock lock;
        public Job(Lock lock){
            this.lock=lock;
        }
        public void run(){

        }
    }

    private static class ReentrantLock2 extends ReentrantLock{
        public ReentrantLock2(boolean fair){
            super(fair);
        }

        public Collection<Thread> getQueueThread(){
            ArrayList<Thread> threadArrayList = new ArrayList<>(super.getQueuedThreads());
            Collections.reverse(threadArrayList);
            return threadArrayList;
        }
    }
}
